package flc.ast.activity;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;

import android.app.Dialog;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.blankj.utilcode.util.ImageUtils;
import com.blankj.utilcode.util.TimeUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.bumptech.glide.Glide;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.stark.imgedit.view.imagezoom.ImageViewTouchBase;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import flc.ast.BaseAc;
import flc.ast.HomeActivity;
import flc.ast.R;
import flc.ast.adapter.AlbumAdapter;
import flc.ast.adapter.StickerAdapter;
import flc.ast.bean.MyAlbumBean;
import flc.ast.bean.MyStickerBean;
import flc.ast.databinding.ActivityAddStickerBinding;
import flc.ast.utils.AppSpUtils;
import io.reactivex.rxjava3.core.ObservableEmitter;
import stark.common.basic.utils.FileUtil;
import stark.common.basic.utils.RxUtil;
import stark.common.basic.view.container.StkRecycleView;

public class AddStickerActivity extends BaseAc<ActivityAddStickerBinding> {

    public static String imgPath = "";
    private StickerAdapter stickerAdapter;
    private int oldPosition;
    private List<String> listSel = new ArrayList<>();
    private AlbumAdapter albumAdapter;
    private Dialog mySelAlbumDialog;
    private Dialog myAddAlbumDialog;
    private EditText dialogAdd;

    @Override
    protected int onCreate() {
        return R.layout.activity_add_sticker;
    }

    @Override
    protected void initView() {
        mDataBinding.ivAddStickerBack.setOnClickListener(v -> onBackPressed());

        mDataBinding.ivAddStickerSave.setOnClickListener(this);

        mDataBinding.rvStickerList.setLayoutManager(new LinearLayoutManager(mContext, LinearLayoutManager.HORIZONTAL, false));
        stickerAdapter = new StickerAdapter();
        mDataBinding.rvStickerList.setAdapter(stickerAdapter);
        stickerAdapter.setOnItemClickListener(this);

        albumAdapter = new AlbumAdapter();
        albumAdapter.setEdit(true);
        albumAdapter.setOnItemClickListener(this);

        //选择相册弹框
        selAlbumDialog();

    }

    @Override
    protected void onClickCallback(View v) {
        switch (v.getId()) {
            case R.id.ivAddStickerSave://保存
                getAlbumData();
                mySelAlbumDialog.show();
                break;
            //选择相册弹框
            case R.id.tvDialogSelAlbumCancel://取消
                mySelAlbumDialog.dismiss();
                break;
            case R.id.tvDialogSelAlbumConfirm://确定
                if (listSel.size() == 0) return;
                saveImg();
                break;
            //新建相册弹框
            case R.id.ivDialogAddAlbumConfirm://确定
                addAlbum();
                break;
            case R.id.ivDialogAddAlbumCancel://取消
                myAddAlbumDialog.dismiss();
                break;
        }
    }

    @Override
    protected void onItemClickCallback(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
        if (adapter == stickerAdapter) {
            stickerAdapter.getItem(oldPosition).setSelect(false);
            stickerAdapter.notifyItemChanged(oldPosition);
            oldPosition = position;
            stickerAdapter.getItem(position).setSelect(true);
            stickerAdapter.notifyItemChanged(position);
            Resources res = getResources();
            Bitmap bmp = BitmapFactory.decodeResource(res, stickerAdapter.getItem(position).getImg());
            mDataBinding.ivStickerView.addBitImage(bmp);
        } else if (adapter == albumAdapter) {
            if (position == 0) {
                //新建相册弹框
                addAlbumDialog();
                myAddAlbumDialog.show();
                return;
            }
            if (albumAdapter.getItem(position).isSelected()) {
                albumAdapter.getItem(position).setSelected(false);
                listSel.remove(albumAdapter.getItem(position).getId());
            } else {
                albumAdapter.getItem(position).setSelected(true);
                listSel.add(albumAdapter.getItem(position).getId());
            }
            albumAdapter.notifyItemChanged(position);
        }
    }

    @Override
    protected void initData() {
        //获取图片
        if (imgPath == null || TextUtils.isEmpty(imgPath)) return;
        Glide.with(this).load(imgPath).into(mDataBinding.imageViewTouch);
        mDataBinding.imageViewTouch.setDisplayType(ImageViewTouchBase.DisplayType.FIT_TO_SCREEN);
        mDataBinding.imageViewTouch.setScaleEnabled(false);// 禁用缩放
        //贴纸数据
        List<MyStickerBean> listSticker = new ArrayList<>();
        listSticker.add(new MyStickerBean(R.drawable.tz_1, getString(R.string.sticker_name, 1), false));
        listSticker.add(new MyStickerBean(R.drawable.tz_2, getString(R.string.sticker_name, 2), false));
        listSticker.add(new MyStickerBean(R.drawable.tz_3, getString(R.string.sticker_name, 3), false));
        listSticker.add(new MyStickerBean(R.drawable.tz_4, getString(R.string.sticker_name, 4), false));
        listSticker.add(new MyStickerBean(R.drawable.tz_5, getString(R.string.sticker_name, 5), false));
        listSticker.add(new MyStickerBean(R.drawable.tz_6, getString(R.string.sticker_name, 6), false));
        listSticker.add(new MyStickerBean(R.drawable.tz_7, getString(R.string.sticker_name, 7), false));
        listSticker.add(new MyStickerBean(R.drawable.tz_8, getString(R.string.sticker_name, 8), false));
        listSticker.add(new MyStickerBean(R.drawable.tz_9, getString(R.string.sticker_name, 9), false));
        listSticker.add(new MyStickerBean(R.drawable.tz_10, getString(R.string.sticker_name, 10), false));
        stickerAdapter.setList(listSticker);
    }

    //保存图片
    private void saveImg() {
        showDialog(getString(R.string.saving));
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                RxUtil.create(new RxUtil.Callback<String>() {

                    @Override
                    public void doBackground(ObservableEmitter<String> emitter) {
                        Bitmap bitmap = ImageUtils.view2Bitmap(mDataBinding.rlStickerSave);
                        //保存到手机相册
                        File file = ImageUtils.save2Album(bitmap, Bitmap.CompressFormat.PNG);
                        List<MyAlbumBean> listSp = AppSpUtils.getPicAlbumList();
                        if (listSp != null && listSp.size() > 0) {
                            for (MyAlbumBean bean : listSp) {
                                for (String s : listSel) {
                                    if (bean.getId().equals(s)) {
                                        List<String> listSave = new ArrayList<>();
                                        listSave.add(file.getPath());
                                        if (bean.getListData() != null && bean.getListData().size() > 0) {
                                            bean.getListData().addAll(listSave);
                                        } else {
                                            bean.setListData(listSave);
                                        }
                                        break;
                                    }
                                }
                            }
                            AppSpUtils.savePicAlbumList(listSp);
                            emitter.onNext("");
                        }
                    }

                    @Override
                    public void accept(String path) {
                        dismissDialog();
                        ToastUtils.showShort(R.string.save_success);
                        startActivity(HomeActivity.class);
                    }
                });
            }
        }, 1000);
    }

    private void getAlbumData() {
        List<MyAlbumBean> listSp = AppSpUtils.getPicAlbumList();
        if (listSp == null) {
            listSp = new ArrayList<>();
        }
        listSp.add(0, new MyAlbumBean());
        if (listSp != null && listSp.size() > 0) {
            albumAdapter.setList(listSp);
        }
    }

    private void addAlbum() {
        String albumName = dialogAdd.getText().toString();
        if (TextUtils.isEmpty(albumName)) {
            ToastUtils.showShort(R.string.please_input_album_name);
            return;
        }
        myAddAlbumDialog.dismiss();
        //准备数据
        List<MyAlbumBean> listSave = new ArrayList<>();
        listSave.add(new MyAlbumBean(TimeUtils.getNowString(), albumName, "", new ArrayList<>(), false));
        //保存数据
        List<MyAlbumBean> listSp = AppSpUtils.getPicAlbumList();
        if (listSp != null && listSp.size() > 0) {
            listSp.addAll(listSave);
            AppSpUtils.savePicAlbumList(listSp);
        } else {
            AppSpUtils.savePicAlbumList(listSave);
        }
        getAlbumData();
    }

    //选择相册弹框
    private void selAlbumDialog() {
        mySelAlbumDialog = new Dialog(mContext, R.style.DialogStyle);
        View inflate = LayoutInflater.from(mContext).inflate(R.layout.dialog_sel_album, null);
        mySelAlbumDialog.setContentView(inflate);
        mySelAlbumDialog.setCancelable(true);
        Window dialogWindow = mySelAlbumDialog.getWindow();
        //设置Dialog从窗体底部弹出
        dialogWindow.setGravity(Gravity.BOTTOM);
        DisplayMetrics dm = getResources().getDisplayMetrics();
        //获得窗体的属性
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        lp.width = (int) (dm.widthPixels * 1.0);
        // 将属性设置给窗体
        dialogWindow.setAttributes(lp);
        TextView right = inflate.findViewById(R.id.tvDialogSelAlbumConfirm);
        TextView cancel = inflate.findViewById(R.id.tvDialogSelAlbumCancel);
        StkRecycleView recycleView = inflate.findViewById(R.id.rvAlbumList);
        recycleView.setLayoutManager(new GridLayoutManager(mContext, 3));
        recycleView.setAdapter(albumAdapter);
        right.setOnClickListener(this);
        cancel.setOnClickListener(this);
    }

    //新建相册弹框
    private void addAlbumDialog() {
        myAddAlbumDialog = new Dialog(mContext, R.style.DialogStyle);
        View inflate = LayoutInflater.from(mContext).inflate(R.layout.dialog_add_album, null);
        myAddAlbumDialog.setContentView(inflate);
        myAddAlbumDialog.setCancelable(true);
        Window dialogWindow = myAddAlbumDialog.getWindow();
        //设置Dialog从窗体底部弹出
        dialogWindow.setGravity(Gravity.CENTER);
        DisplayMetrics dm = getResources().getDisplayMetrics();
        //获得窗体的属性
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        lp.width = (int) (dm.widthPixels * 1.0);
        // 将属性设置给窗体
        dialogWindow.setAttributes(lp);
        ImageView right = inflate.findViewById(R.id.ivDialogAddAlbumConfirm);
        ImageView cancel = inflate.findViewById(R.id.ivDialogAddAlbumCancel);
        dialogAdd = inflate.findViewById(R.id.etDialogAddAlbumText);
        right.setOnClickListener(this);
        cancel.setOnClickListener(this);
    }

}